<?php
class Category_model extends Model {

    var $category_id = '';
    var $name = '';
	var $created = '';
	var $changed = '';

    function Category_model()
    {
        // Call the Model constructor
        parent::Model();
    }
    
    function get_all()
    {
		$this->db->order_by('name');
        $query = $this->db->get('category');
        return $query->result();
    }
	
	function get_category($id)
	{
		$this->db->where('category_id',$id);
		$query = $this->db->get('category');
		if( $query->num_rows() > 0){
			$row = $query->row();
			$this->category_id = $row->category_id;
			$this->name = $row->name;
			$this->created = $row->created;
			$this->changed = $row->changed;
			return $row;
		}
		else{
			return FALSE;
		}
	}
	
	function get_first(){
		$this->db->order_by('name');
		$this->db->limit(1);
		$query = $this->db->get('category');
		$row = $query->row();
		return $row->category_id;
	}
	
	function get_max_position($id)
	{
		$this->db->select_max('position');
		$this->db->where('category_id',$id);
		$query = $this->db->get('photo');
		if($query->num_rows() > 0){
			$row = $query->row();
			return $row->position;
		}
       	else{
			return 0;
		}
	}

    function insert()
    {
        $this->category_id = $this->input->post('category_id');
		$this->name = $this->input->post('name');
		$this->created = time();
		$this->changed = time();
		
		if(trim($this->category_id) == ''){
			$this->session->set_flashdata('msg', 'id cannot be empty');
			return FALSE;
		}
		else{
	        $this->db->insert('category', $this);
			$this->session->set_flashdata('msg', $this->db->_error_message());
			return $this->db->trans_status();
		}
    }

    function update()
    {
        $this->category_id = $this->input->post('category_id');
        $this->name = $this->input->post('name');
		$this->changed = time();
        $this->db->update('category', $this, array('category_id' => $this->input->post('category_id')));
		return $this->db->trans_status();
    }

	function exists($id){
		$this->db->from('category');
		$this->db->where('category_id',$id);
		if($this->db->count_all_results() >= 1)
			return TRUE;
		else
			return FALSE;
	}
}
?>